package com.example.library.service.impl;

import com.example.library.entity.Book;
import com.example.library.mapper.BookMapper;
import com.example.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Override
    public Map<String, Object> getBooks(int page, int size) {
        int offset = (page - 1) * size;
        List<Book> books = bookMapper.findAll(offset, size);
        int total = bookMapper.count();

        Map<String, Object> result = new HashMap<>();
        result.put("books", books);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (total + size - 1) / size);
        return result;
    }

    @Override
    public Book getBookById(Long id) {
        Book book = bookMapper.findById(id);
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        return book;
    }

    @Override
    public List<Book> searchBooks(String keyword) {
        return bookMapper.search(keyword);
    }

    @Override
    public Book addBook(Book book) {

        List<Book> existing = bookMapper.search(book.getIsbn());
        if (!existing.isEmpty()) {
            throw new RuntimeException("该ISBN已存在");
        }
        bookMapper.insert(book);
        return book;
    }

    @Override
    public Book updateBook(Long id, Book book) {

        Book existing = bookMapper.findById(id);
        if (existing == null) {
            throw new RuntimeException("图书不存在");
        }
        book.setId(id);
        bookMapper.update(book);
        return bookMapper.findById(id);
    }

    @Override
    public void deleteBook(Long id) {
        Book book = bookMapper.findById(id);
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        bookMapper.delete(id);
    }
}